package com.nakamachizu.service.mixi;

import java.util.Calendar;

import org.apache.commons.lang.RandomStringUtils;
import org.slim3.datastore.Datastore;
import org.slim3.util.TimeZoneLocator;

import com.nakamachizu.meta.session.MixiFriendSessionMeta;
import com.nakamachizu.meta.session.MixiSessionDataMeta;
import com.nakamachizu.model.session.MixiFriendSession;


public class SessionService {
    
    public String makeMixiSessionKey() throws Exception{
        MixiSessionDataMeta meta = MixiSessionDataMeta.get();
        String accessKey = RandomStringUtils.randomAlphanumeric(24);
        int i=0;
        while(Datastore.query(meta).filter(meta.accessKey.equal(accessKey)).countQuickly() > 0){
            accessKey = RandomStringUtils.randomAlphanumeric(24);
            i++;
            if(i>100){
                throw new Exception("generate mixi session id failed.");
            }
        }
        return accessKey;
    }

    public MixiFriendSession getMixiFriendSession(String mixiId){
        Calendar now = Calendar.getInstance(TimeZoneLocator.get());
        MixiFriendSessionMeta meta = MixiFriendSessionMeta.get();
        return Datastore.query(meta).filter(meta.mixiId.equal(mixiId), meta.expireDate.greaterThan(now.getTime())).asSingle();
    }
}
